package dynamicloader.windy.com.dynamicloader;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.windy.dynamicloader.IEncrypt;

import java.io.File;

import dalvik.system.DexClassLoader;

/**
 * Created by admin on 2015/12/24.
 */
public class DynamicEncryptActivity extends Activity implements View.OnClickListener {

    private static final String TAG = "DynamicEncryptActivity";
    private int randomNum = 1;
    private IEncrypt encrypt = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_encrypt);
        
        findViewById(R.id.btn_encrypt).setOnClickListener(this);
        findViewById(R.id.btn_random).setOnClickListener(this);
        findViewById(R.id.btn_load).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_encrypt:
                encrypt();
                break;
            
            case R.id.btn_random:
                random();
                break;
            
            case R.id.btn_load:
                load();
                break;
        }
    }

    private void load() {
        String path = Environment.getExternalStorageDirectory() + File.separator + "encrypt" + randomNum + ".jar";
        DexClassLoader loader = new DexClassLoader(path, getFilesDir().toString(), null, getClassLoader());
        try {
            Class tmpClass = loader.loadClass("com.windy.dynamicloader.Encrypter");
            try {
                encrypt = (IEncrypt) tmpClass.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void random() {
        randomNum = (int)((Math.random() * 1000) % 3) + 1; // randomNum is from 1 to 3
        Log.d(TAG, "random num is:" + randomNum);
    }

    private void encrypt() {
        if (encrypt != null) {
            Toast.makeText(this, encrypt.encrypt("origin message"), Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "encrypt method not load yet", Toast.LENGTH_SHORT).show();
        }
    }
}
